import type { DataNamespace, DataType } from "../types";

/**
 * 数据管理
 */
export class PtData {
    private data: DataType;
    private defaultNamespace: DataNamespace;

    constructor(data: DataType, defaultNamespace: DataNamespace = 'base') {
        this.data = data;
        this.defaultNamespace = defaultNamespace;
    }

    public get<T = any>(key: string, namespace: DataNamespace = this.defaultNamespace): T {
        key = key || '';

        if (key == '') {
            return null as T;
        }

        let origin: DataType = this.data;

        // 例如 student:id 指定了从student集中获取id字段
        const [ns, nk] = key.split(':');

        if (nk) {
            key = nk;
            namespace = ns;
        }

        if (typeof namespace == 'string') {
            if (namespace != '') {
                origin = this.trimPath(namespace.split('.'), this.data);
            }
        } else {
            origin = namespace;
        }

        return this.trimPath(key.split('.'), origin);
    }

    public getString(field: string, namespace: DataNamespace = this.defaultNamespace): string {
        const value = this.get(field, namespace);

        if (value == null) {
            return '';
        }

        if (typeof value == 'object') {
            return '';
        }

        return String(value);
    }

    private trimPath(keys: string[], data: DataType): any {
        let value = data;

        for (const f of keys) {
            if (!value || !(f in value)) {
                return null;
            }

            value = value[f];
        }

        return value;
    }

    public getRaw(): DataType {
        return this.data;
    }
}